#ifndef MIN_HEAP
#define MIN_HEAP

#include <iostream>
#include <functional>
#include <chrono>
#include <vector>
#include <algorithm>
#include <memory>
#include <netinet/in.h>

using Clock = std::chrono::steady_clock;
using TimePoint = Clock::time_point;
using Duration = Clock::duration;

constexpr int BUFFER_SIZE = 64;

class heapTimer;
struct clientData {
    sockaddr_in address;
    int sockFd;
    char buf[BUFFER_SIZE];
    std::shared_ptr<heapTimer> timer;
};

class heapTimer : public std::enable_shared_from_this<HeapTimer>{
private:
    TimePoint expireTime;  // 绝对超时时间点
    Callback callback;     // 回调函数
    std::shared_ptr<ClientData> clientData;  // 关联的客户端数据
public:
    using Callback = std::function<void(std::shared_ptr<ClientData>)>;
    explicit HeapTimer(Duration timeout)
        : expireTime(Clock::now() + timeout) {}
    
    // 判断定时器是否超时
    bool isExpired() const {
        return Clock::now() >= expireTime;
    }

    // 获取剩余时间
    Duration remainingTime() const {
        return std::max(expireTime - Clock::now(), Duration::zero());
    }

    // 设置回调函数
    void setCallback(Callback cb) {
        callback = std::move(cb);
    }

    // 设置关联的客户端数据
    void setClientData(std::shared_ptr<ClientData> data) {
        clientData = std::move(data);
    }

    // 执行回调函数
    void execute() const {
        if (callback && clientData) {
            callback(clientData);
        }
    }

    // 比较运算符重载，用于堆排序
    bool operator>(const HeapTimer& other) const {
        return expireTime > other.expireTime;
    }
};

class timeHeap {
private:
    std::vector<std::shared_ptr<HeapTimer>> heap;  // 最小堆存储容器

private:
    void adjustDown(int root) {
        int n = heap.size();
        int child = root * 2 + 1;
        while(child < n) {
            if (child < n - 1 && heap[child + 1]->expire < heap[child]->expire) {
                child++;
            }
            if (heap[parent] > heap[index]) {
                std::swap(heap[child], heap[root]);
            }
            else {
                break;
            }
            root = child;
            child = root * 2 + 1;
        }
    }

    void adjustUp(int index) {
        while(index > 0) {
            int parent = (index - 1) / 2;
            if(heap[parent] <= heap[index]) {
                break;
            }
            std::swap(heap[parent], heap[index]);
            index = parent;
        }
    }

public:
    void addTimer(std::shared_ptr<HeapTimer> timer) {
        if(!timer) {
            return;
        }
        heap.push_back(timer);
        int index = heap.size() - 1;
        adjustUp(index);
    }

    void removeTimer(const std::shared_ptr<HeapTimer>& timer) {
        if (!timer) 
            return;
        for (int i = 0; i < heap.size(); ++i) {
            if (heap[i] == timer) {
                heap[i] = heap.back();
                heap.pop_back();
                if (i < heap.size()) {
                    adjustDown(i);
                    adjustUp(i);
                }
                break;
            }
        }
    }

    // 获取堆顶定时器（最早超时的）
    std::shared_ptr<HeapTimer> top() {
        if(!heap.empty()) {
            return nullptr;
        }
        return heap.front();
    }

    // 删除堆顶元素
    void pop() {
        if (heap.empty()) 
            return;
        
        heap.front() = std::move(heap.back());
        heap.pop_back();
        if (!heap.empty()) 
            adjustDown(0);
    }

    void tick() {
        while (!heap.empty() && top()->isExpired()) {
            top()->execute();
            pop();
        }
    }

    // 获取下一个定时器的剩余时间（毫秒）
    std::chrono::milliseconds getNextExpiration() const {
        if (heap.empty()) 
            return std::chrono::milliseconds(-1);
        return std::chrono::duration_cast<std::chrono::milliseconds>(top()->remainingTime());
    }
};

#endif  // MIN_HEAP